package com.cskaoyan.javase.practice.stage6.utils;

import com.cskaoyan.javase.practice.stage6.entity.Student;

/**
 * @program: little-practice
 * @description:
 * @author: Keyu Li
 * @create: 2021-09-11 15:51
 **/

public class StringUtils {
    public static final char SEPARATOR = Student.SEPARATOR;

    private StringUtils(){
    }

    public static int parseToStuNum(String s){
        // 第一行格式为；student total number: 5
        // 从中提取数量
        char[] chars = s.toCharArray();
        int index = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ':'){
                index = i;
                break;
            }
        }
        if (index==-1) return -1;
        return Integer.parseInt(s.substring(index+1).trim());
    }

    public static Student parseToStu(String s){
        // String存储格式如：Student{stuId='2', name='王五', gender='男', age='8', grade='小班', tele='13356577723'}
        // 元素取值在 '' 之内，存储每一个 ' 对应的 char下标。
        int elementNum = Student.ELEMENT_NUMBER;
        char[] chars = s.toCharArray();
        int[] elementIndex = new int[2*elementNum];
        int index = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i]!=SEPARATOR) continue;
            elementIndex[index++] = i;
        }

        // 截取相应字符串然后存储到字符串数组中
        String[] elementString = new String[elementNum];
        for (int i = 0; i < elementIndex.length; i+=2) {
            // 注意截取字符串时候，前闭后开。
            elementString[i/2] = s.substring(elementIndex[i]+1, elementIndex[i+1]);
        }

        // 将相应字符串转换为 student 属性值
        int stuId = Integer.parseInt(elementString[0]);
        String name = elementString[1];
        String gender = elementString[2];
        int age = Integer.parseInt(elementString[3]);
        String grade = elementString[4];
        String tele = elementString[5];

        // 返回student对象
        return new Student(stuId,name,gender,age,grade,tele);
    }
}
